import { IconFont } from '@/components';
import { View, Text, Image } from '@ray-js/ray';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import dayjs from 'dayjs';
import Styles from './switchAnalyze.module.less';
import res from '@/res/image';

interface SwitchAnalyzeProps {
  onDateChange: (date: number) => void;
  date: number;
  range: 'day' | 'month' | 'year' | 'week';
}

export const SwitchAnalyze = ({ onDateChange, date, range }: SwitchAnalyzeProps) => {
  const onPrev = useCallback(() => {
    let prev;
    if (range === 'day') {
      prev = dayjs(date).subtract(1, 'day').valueOf();
    } else if (range === 'month') {
      prev = dayjs(date).subtract(1, 'month').valueOf();
    } else if (range === 'year') {
      prev = dayjs(date).subtract(1, 'year').valueOf();
    } else {
      prev = dayjs(date).subtract(7, 'day').valueOf();
    }

    onDateChange(prev);
  }, [date, range]);

  const onNext = useCallback(() => {
    let next;
    if (diableNext) return;
    if (range === 'day') {
      next = dayjs(date).add(1, 'day').valueOf();
    } else if (range === 'month') {
      next = dayjs(date).add(1, 'month').valueOf();
    } else if (range === 'year') {
      next = dayjs(date).add(1, 'year').valueOf();
    } else {
      next = dayjs(date).add(7, 'day').valueOf();
    }

    onDateChange(next);
  }, [date, range]);

  const diableNext = useMemo(() => {
    if (range === 'day') {
      return dayjs(date).startOf('day').valueOf() === dayjs().startOf('day').valueOf();
    }
    if (range === 'month') {
      return dayjs(date).startOf('month').valueOf() === dayjs().startOf('month').valueOf();
    }
    if (range === 'year') {
      return dayjs(date).startOf('year').valueOf() === dayjs().startOf('year').valueOf();
    }
    //   return dayjs(date).startOf('week').valueOf() === dayjs().startOf('week').valueOf();
    return (
      dayjs(date).startOf('week').add(1, 'day').valueOf() ===
      dayjs().startOf('week').add(1, 'day').valueOf()
    );
  }, [date, range]);

  const formatText = useMemo(() => {
    if (range === 'day') {
      return dayjs(date).format('YYYY-MM-DD');
    }
    if (range === 'month') {
      return dayjs(date).format('YYYY-MM');
    }

    if (range === 'year') {
      return dayjs(date).format('YYYY');
    }
    if (range === 'week') {
      return `${dayjs(date).startOf('week').add(1, 'day').format('YYYY-MM-DD')} - ${dayjs(date)
        .endOf('week')
        .add(1, 'day')
        .format('YYYY-MM-DD')}`;
    }
  }, [date, range]);

  return (
    <View className={Styles.wrapper}>
      <View className={Styles.nav} onClick={onPrev}>
        <Image src={res.timePrev} className={Styles.icon} />
      </View>
      <Text style={{ color: 'white' }}>{formatText}</Text>
      <View className={Styles.nav} style={{ opacity: diableNext ? 0.4 : 1 }} onClick={onNext}>
        <Image src={res.timeNext} className={Styles.icon} />
      </View>
    </View>
  );
};
